package com.jakewharton.rxbinding4.component;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.TimePicker;

final class TimePickerTimeChangeEventObservable extends InitialValueObservable<TimePickerTimeChangeEvent> {
    private final TimePicker view;

    TimePickerTimeChangeEventObservable(@NonNull TimePicker view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super TimePickerTimeChangeEvent> observer) {
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.setTimeChangedListener(listener);
    }

    @Override
    protected TimePickerTimeChangeEvent getInitialValue() {
        return TimePickerTimeChangeEvent.create(view, view.getHour(), view.getMinute(), view.getSecond());
    }

    static final class Listener extends MainThreadDisposable implements TimePicker.TimeChangedListener {
        private final TimePicker view;
        private final Observer<? super TimePickerTimeChangeEvent> observer;

        Listener(TimePicker view, Observer<? super TimePickerTimeChangeEvent> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setTimeChangedListener(null);
        }

        @Override
        public void onTimeChanged(TimePicker timePicker, int hour, int minute, int second) {
            if (!isDisposed()) {
                observer.onNext(TimePickerTimeChangeEvent.create(view, hour, minute, second));
            }
        }
    }
}
